package com.pansoft.openplanet.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.FragmentContainActivity;
import com.efounder.adapter.MenuListViewAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.zxing.qrcode.MipcaActivityCapture;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.fragment.MenuFragment;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.model.RefreshMainNineGridViewEvent;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.StorageUtil;
import com.efounder.util.ToastUtil;
import com.pansoft.openplanet.activity.TabBottomActivityForTalkChain;
import com.pansoft.resmanager.ResFileManager;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import static com.efounder.forwechat.BaseApp.context;

//import com.pansoft.xmlparse.MenuList;
//import com.pansoft.xmlparse.MenuParse;

public class OpenMenuFragment extends BaseFragment implements OnClickListener {
    /* menu配置菜单路径 */
    private static final String MENU_FILE_PATH = ResFileManager.PACKAGE_DIR
            + "/" + "Tab_Menu.xml";
    /* 主页3级菜单id */
    private String EXT_EDGEMENU_ROOT = "zy";

    // listView 列表
    private ListView menuListView;

    private List<StubObject> extEdgeMenus;
    private final String CAPTION = "caption";
    private final String URL = "url";
    private final String VIEWTYPE = "viewType";
    private final String NORMALICON = "normalIcon";
    private Boolean isShowBottom;
    private StorageUtil storageUtil;
    private Boolean isAllSelected;// 是否全部选中
    private ImageView allImageView;// 全部选中按钮

    private TextView tongjiTextView;

    //首页fragment回调
    private MenuFragment.RefreshforDefineMenu mListener;

    //listadapter
    private MenuListViewAdapter menuListViewAdapter;

    private String fromString;

    private View rootView;
    private Button save_menu;

    public OpenMenuFragment() {
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (MenuFragment.RefreshforDefineMenu) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + "must implement RefreshforDefineMenu");
        }
    }

    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.menufragment_new, null);
        rootView.setOnClickListener(this);

        //--------------------------处理title
        RelativeLayout include = (RelativeLayout) rootView.findViewById(R.id.include);
        TextView title = (TextView) rootView.findViewById(R.id.fragmenttitle);
        title.setText("更多");
        LinearLayout leftbacklayout = (LinearLayout) rootView.findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);

        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                OpenMenuFragment.this.getFragmentManager().popBackStack();
            }
        });

        save_menu = (Button) rootView.findViewById(R.id.save_menu);

        save_menu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (extEdgeMenus == null) {
                    return;
                }

                LoadingDataUtilBlack.show(OpenMenuFragment.this.getContext(), "正在保存");
                //1.先将配置信息持久化
                Map.Entry entry;
                StringBuffer sb = new StringBuffer();
                Map<String, String> localMap = new HashMap();
                String userName = EnvironmentVariable.getUserName();
                String localString = EnvironmentVariable.getProperty(userName + "/" + fromString, "");
                if (!localString.equals("")) {
                    StringTokenizer items;
                    for (StringTokenizer entrys = new StringTokenizer(localString, "^"); entrys.hasMoreTokens();
                         localMap.put(items.nextToken(), items.hasMoreTokens() ? ((String) (items.nextToken())) : null))
                        items = new StringTokenizer(entrys.nextToken(), "'");
                }
                //2.处理角标
                String badgeTypeArrayString = "";
                String badgeNoShow = "";
                List<String> appIDList = new ArrayList<>();
                //String[] badgeTypeArray = badgeTypeArrayString.split(",");

                for (int i = 0; i < extEdgeMenus.size(); i++) {
                    StubObject stubObject = extEdgeMenus.get(i);
                    String id = stubObject.getString("id", "").toString();
                    boolean isChecked = stubObject.getBoolean("ischecked", true);
                    if (null != localMap.get(id)) {
                        if (isChecked) {
                            localMap.put(id, "1");
                        } else {
                            localMap.put(id, "0");
                        }
                    }

                    String appId = stubObject.getString("appId", "");
                    if (!appId.equals("")) {
                        appIDList.add(appId);
                        if (isChecked) {
                            badgeNoShow += "," + appId;
                        } else {
                            badgeTypeArrayString += "," + appId;
                        }
                    }
                }


                for (Iterator iterator = localMap.entrySet().iterator(); iterator.hasNext(); ) {
                    entry = (Map.Entry) iterator.next();
                    sb.append(entry.getKey().toString()).append("'").append(null == entry.getValue() ? "" :
                            entry.getValue().toString()).append(iterator.hasNext() ? "^" : "");
                }

                EnvironmentVariable.setProperty(userName + "/" + fromString, sb.toString());

                EnvironmentVariable.setProperty("BadgeNoShow" + OpenMenuFragment.this.getBadgeType(), badgeNoShow);
                EnvironmentVariable.setProperty("Badge" + OpenMenuFragment.this.getBadgeType(), badgeTypeArrayString);

                //刷新主界面
                if (null != mListener) {
                    mListener.refreshNotice();
                }else{
                    //兼容操作 eventbus 事件
                    EventBus.getDefault().post(new RefreshMainNineGridViewEvent() );
                }

                //发送角标更新事件
                BadgeUtil.initBadge();
                for (int i = 0; i < appIDList.size(); i++) {
                    UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(appIDList.get(i), (byte) 2);
                    updateBadgeViewEvent.setRefreshAll(true);
                    EventBus.getDefault().post(updateBadgeViewEvent);
                }


                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToast(OpenMenuFragment.this.getContext(), "保存成功");
                OpenMenuFragment.this.getFragmentManager().popBackStack();


            }
        });

        //--------------------------处理title结束

        // 不是全部选中状态，全选按钮为未选择
        storageUtil = new StorageUtil(getActivity().getApplicationContext(),
                "storage");
        isAllSelected = storageUtil.getBoolean("isAllSelected", true);
        allImageView = (ImageView) rootView
                .findViewById(R.id.tongjiimagebutton);
        allImageView.setOnClickListener(this);

        tongjiTextView = (TextView) rootView.findViewById(R.id.tongji);


        menuListView = (ListView) rootView.findViewById(R.id.menulist);
        menuListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                StubObject nowStubObejct = (StubObject) extEdgeMenus
                        .get(position);
                String direction = nowStubObejct.getString("tabID", null);
                Hashtable menuTable = nowStubObejct.getStubTable();
                String viewType = (String) menuTable.get("viewType");
                int positionbottom = 0;
                AbFragmentManager ab = new AbFragmentManager(context);


                if ("display".equals(viewType)) {
                    try {
                        ab.startActivity(nowStubObejct, 0, 0);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else if ("appacount".equals(viewType)) {
                    //跳转公众号
                    User user = WeChatDBManager.getInstance().
                            getOneOfficialNumber(Integer.valueOf((String) menuTable.get("appId")));
                    if (user == null) {
                        ToastUtil.showToast(context, "您没有关注此公众号");
                        return;
                    }
                    Intent intent = null;
//                    if (user.getId() == 2307){//代记账应用号-2307
//                        intent = new Intent(getActivity(), EFAppAccountDJZMainActivity.class);
//                    }else {
//                        intent = new Intent(getActivity(), EFAppAccountMainActivity.class);
//                    }
                    intent = new Intent(getActivity(), EFAppAccountMainActivity.class);
                    intent.putExtra("id", Integer.valueOf((String) menuTable.get("appId")));
                    intent.putExtra("nickName", (String) menuTable.get("caption"));
                    getActivity().startActivity(intent);

                } else if ("saoyisao".equals(viewType)) {
                    Intent intent = new Intent(getActivity(), MipcaActivityCapture.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    getActivity().startActivity(intent);
                } else if ("ywfw".equals(viewType)) {
                    try {
                        Intent intent = new Intent(context, Class.forName("com.efounder.RNCWGXActivity"));
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    Intent intent = new Intent(OpenMenuFragment.this.getActivity(),
                            FragmentContainActivity.class);
                    intent.putExtra("type",
                            (StubObject) extEdgeMenus.get(position));
                    OpenMenuFragment.this.getActivity().startActivity(intent);
                }


                // }

            }
        });
        // 获取数据
        getSlideData();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        //此处处理不显示下面的tabbottombar
        TabBottomActivityForTalkChain menuFrag = TabBottomActivityForTalkChain.getInstance();
        isShowBottom = (menuFrag.getBottomBar().getVisibility() == View.VISIBLE);
        if (isShowBottom)
            menuFrag.getBottomBar().setVisibility(View.GONE);
    }

    @Override
    public void onStop() {
        super.onStop();
        //此处处理显示下面的tabbottombar
        if (isShowBottom) {
            TabBottomActivityForTalkChain menuFrag = TabBottomActivityForTalkChain.getInstance();
            menuFrag.getBottomBar().setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //此处处理显示下面的tabbottombar
        if (isShowBottom) {
            TabBottomActivityForTalkChain menuFrag = TabBottomActivityForTalkChain.getInstance();
            menuFrag.getBottomBar().setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /*
     * 放置抽屉数据源
     */
    private void getSlideData() {

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // data是测试数据(假数据)
                // fakeData();
                // 后台下载并解析菜单, 并且获取主菜单
                File file = new File(MENU_FILE_PATH);
                // TODO
                // MenuList.clearRegistry();
//                MenuParse.getMenu(file);
                // ESPMenuUtils.getMainMenus();
//                extEdgeMenus = MenuList.getMenuList(EXT_EDGEMENU_ROOT);
                extEdgeMenus = Registry.getRegEntryList(EXT_EDGEMENU_ROOT);

                int j = 0;
                for (int i = 0; i < extEdgeMenus.size(); i++) {

                    // 权限判断
                    StubObject soObject = (StubObject) extEdgeMenus.get(i);

                    if (!com.efounder.util.SecurityManager.checkGNQXWithStub(
                            OpenMenuFragment.this.getActivity(), soObject)) {
                        extEdgeMenus.remove(i - j);
                        j++;
                    }

                }

                return null;
            }

            @SuppressLint("NewApi")
            protected void onPostExecute(Void result) {
                // 加载完主菜单之后调用, 用于显示主菜单等操作
                if (extEdgeMenus != null && extEdgeMenus.size() != 0) {
                    if (OpenMenuFragment.this.getActivity() == null) return;
                    //ArrayList<Object> ObjectByChoice = FilesOperationDataUtil.readFile(MenuFragment.this.getActivity(), fromString);

                    String userName = EnvironmentVariable.getUserName();


                    String localString = EnvironmentVariable.getProperty(userName + "/" + fromString, "");

                    Map<String, String> localMap = new HashMap();
                    if (!localString.equals("")) {
                        StringTokenizer items;
                        for (StringTokenizer entrys = new StringTokenizer(localString, "^"); entrys.hasMoreTokens();
                             localMap.put(items.nextToken(), items.hasMoreTokens() ? ((String) (items.nextToken())) : null))
                            items = new StringTokenizer(entrys.nextToken(), "'");
                    }

                    //numofISShow 标志着选中的数量
                    int numofISShow = 0;
                    if (!localMap.isEmpty()) {
                        for (int i = 0; i < extEdgeMenus.size(); i++) {
                            StubObject xmlStuObject = extEdgeMenus.get(i);
                            String xmlid = xmlStuObject.getString("id", "");
                            if (localMap.containsKey(xmlid)) {
                                String value = localMap.get(xmlid);
                                if (value.equals("1")) {
                                    xmlStuObject.setBoolean("ischecked", true);
                                    numofISShow++;
                                }
                            }
//                            StubObject objectofFile = (StubObject) ObjectByChoice
//                                    .get(i);
//                            Boolean ischecked = objectofFile.getBoolean(
//                                    "ischecked", true);
//                            String caption = objectofFile
//                                    .getString(CAPTION, "");
//                            if (ischecked) {
//                                for (int j = 0; j < extEdgeMenus.size(); j++) {
//                                    StubObject extEdObject = (StubObject) extEdgeMenus
//                                            .get(j);
//                                    String captionNew = extEdObject.getString(
//                                            CAPTION, "");
//                                    if (caption.equals(captionNew)) {
//                                        extEdObject.setBoolean("ischecked",
//                                                true);
//                                    }
//                                }
//                                numofISShow++;
//                            }

                        }
                        numofISShow--;
                    } else {
                        for (int j = 0; j < extEdgeMenus.size(); j++) {
                            StubObject extEdObject = (StubObject) extEdgeMenus
                                    .get(j);
                            String captionNew = extEdObject.getString(CAPTION,
                                    "");
                            extEdObject.setBoolean("ischecked", true);

                        }
                        numofISShow = extEdgeMenus.size() - 1;

                    }

                    if (numofISShow == extEdgeMenus.size() - 1) {
                        allImageView.setBackground(getResources().getDrawable(
                                R.drawable.menufragment_cancle));
                    } else {
                        allImageView.setBackground(getResources().getDrawable(
                                R.drawable.menufragment_all));
                    }
                    tongjiTextView.setText("共" + (extEdgeMenus.size() - 1)
                            + "个模块");

                    menuListViewAdapter = new MenuListViewAdapter(
                            OpenMenuFragment.this.getActivity(), extEdgeMenus,
                            fromString);
                    menuListView.setAdapter(menuListViewAdapter);

                }

            }

        }.execute();

    }


    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {

    }


    public void setFromString(String fromString) {
        this.fromString = fromString;
    }

    public void setXmlBH(String EXT_EDGEMENU_ROOT) {
        this.EXT_EDGEMENU_ROOT = EXT_EDGEMENU_ROOT;
    }

}
